/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogAddNewUser.java
 *
 * Created on Jun 11, 2012, 9:27:22 PM
 */
package com.ebdesk.view.masterdata;

import com.ebdesk.controller.masterdata.UserController;
import com.ebdesk.controller.masterdata.Validator;
import com.ebdesk.model.masterdata.User;
import com.ebdesk.view.MainFrame;
import java.awt.Color;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Acer
 */
public class DialogAddNewUser extends javax.swing.JDialog {
    public boolean addSuccess;
    private UserController userController;
    private MainFrame parent;
    /** Creates new form DialogAddNewUser */
    public DialogAddNewUser(MainFrame parent, boolean modal) {
        super(parent, modal);
        this.parent = parent;
        
        userController = new UserController();
        
        this.setLocationRelativeTo(null);
        try {
                        // Set System L&F
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                } 
                catch (UnsupportedLookAndFeelException e) {
                   // handle exception
                }
                catch (ClassNotFoundException e) {
                   // handle exception
                }
                catch (InstantiationException e) {
                   // handle exception
                }
                catch (IllegalAccessException e) {
                   // handle exception
                }
        
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        panelInput = new javax.swing.JPanel();
        labelUsername = new javax.swing.JLabel();
        textUsername = new javax.swing.JTextField();
        labelNama = new javax.swing.JLabel();
        textName = new javax.swing.JTextField();
        labelEmail = new javax.swing.JLabel();
        textEmail = new javax.swing.JTextField();
        labelPassword = new javax.swing.JLabel();
        labelRePassword = new javax.swing.JLabel();
        labelUserType = new javax.swing.JLabel();
        comboUserType = new javax.swing.JComboBox();
        buttonSave = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();
        textPassword = new javax.swing.JPasswordField();
        textRePassword = new javax.swing.JPasswordField();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add New User");
        setIconImage(null);
        setModal(true);
        setName("addNewUser"); // NOI18N
        setResizable(false);

        panelInput.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        labelUsername.setFont(new java.awt.Font("Tahoma", 1, 11));
        labelUsername.setText("Username");

        labelNama.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        labelNama.setText("Nama");

        textName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textNameActionPerformed(evt);
            }
        });

        labelEmail.setFont(new java.awt.Font("Tahoma", 1, 11));
        labelEmail.setText("Email");

        labelPassword.setFont(new java.awt.Font("Tahoma", 1, 11));
        labelPassword.setText("Password");

        labelRePassword.setFont(new java.awt.Font("Tahoma", 1, 11));
        labelRePassword.setText("Re Password");

        labelUserType.setFont(new java.awt.Font("Tahoma", 1, 11));
        labelUserType.setText("User Type");

        comboUserType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Admin", "Non Admin" }));

        buttonSave.setFont(new java.awt.Font("Tahoma", 1, 11));
        buttonSave.setText("Save");
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        buttonCancel.setFont(new java.awt.Font("Tahoma", 1, 11));
        buttonCancel.setText("Cancel");
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelInputLayout = new javax.swing.GroupLayout(panelInput);
        panelInput.setLayout(panelInputLayout);
        panelInputLayout.setHorizontalGroup(
            panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelInputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelUsername)
                    .addComponent(labelNama)
                    .addComponent(labelEmail)
                    .addComponent(labelPassword)
                    .addComponent(labelRePassword)
                    .addComponent(labelUserType))
                .addGap(18, 18, 18)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelInputLayout.createSequentialGroup()
                        .addComponent(buttonSave)
                        .addGap(18, 18, 18)
                        .addComponent(buttonCancel))
                    .addComponent(textUsername, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                    .addComponent(textName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                    .addComponent(textEmail, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                    .addComponent(comboUserType, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
                    .addComponent(textRePassword, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE))
                .addContainerGap())
        );
        panelInputLayout.setVerticalGroup(
            panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelInputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelUsername))
                .addGap(18, 18, 18)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelNama))
                .addGap(18, 18, 18)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelEmail)
                    .addComponent(textEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelPassword)
                    .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelRePassword)
                    .addComponent(textRePassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(labelUserType)
                    .addComponent(comboUserType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                .addGroup(panelInputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSave)
                    .addComponent(buttonCancel))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelInput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelInput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void textNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_textNameActionPerformed

private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
    User user = new User();
    user.setUsername(textUsername.getText());
    user.setName(textName.getText());
    boolean ok = false;
    String email = textEmail.getText();
    String error = "";
    if (textUsername.getText().trim().isEmpty()) {
        error += "username tidak boleh kosong.\n";
        ok = false;
        labelUsername.setForeground(Color.red);
    } else {
        ok = true;
        labelUsername.setForeground(Color.black);
    }
    
    if (textName.getText().trim().isEmpty()) {
        error += "name tidak boleh kosong.\n";
        ok = false;
        labelNama.setForeground(Color.red);
    } else {
        ok = ok && true;
        labelEmail.setForeground(Color.black);
    }
    
    if (Validator.isValidEmail(email)) {
        labelEmail.setForeground(Color.black);
        user.setEmail(email);
        ok = ok && true;
    } else {
        //user = null;
        error += "Email Address is not valid, please enter valid address email!\n";
        labelEmail.setForeground(Color.red);
        ok = false;
    }
    
    String password = new String(textPassword.getPassword());
    String rePassword = new String(textRePassword.getPassword());
    if (password.trim().isEmpty()) {
        ok = false;
        error += "Password tidak boleh kosong\n";
        labelPassword.setForeground(Color.red);
    } else {
        if (Validator.isSamePassword(password, rePassword)) {
            labelRePassword.setForeground(Color.black);
            labelPassword.setForeground(Color.black);
            user.setPassword(password);
            ok = ok && true;
        } else {
            //user = null;
            error += "Re Password not same, please enter correct password!";
            labelRePassword.setForeground(Color.red);
            ok = false;
        }
    }
    int success = 0;
    user.setUser_type(comboUserType.getSelectedIndex() + 1);
    user.setCreated_by(parent.getSession().getUser().getUsername());
    if (!ok) {
        JOptionPane.showMessageDialog(this, error, "Error Message", JOptionPane.WARNING_MESSAGE);
    } else {
        try {
            success = userController.getUserManagement().addUser(user);
            if (success == -1) {
                user = null;
                JOptionPane.showMessageDialog(this, "Tidak Boleh!, Username sudah ada. harap menggunakan username yang lain.", "Duplicate Username", JOptionPane.WARNING_MESSAGE);
            }
        } catch (SQLException ex) {
            Logger.getLogger(DialogAddNewUser.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (success != -1) {
            this.setVisible(false);
            addSuccess = true;
        }
    }
}//GEN-LAST:event_buttonSaveActionPerformed

private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
    this.setVisible(false);
}//GEN-LAST:event_buttonCancelActionPerformed

//    /**
//     * @param args the command line arguments
//     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//                
//        //</editor-fold>
//
//        /* Create and display the dialog */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                DialogAddNewUser dialog = new DialogAddNewUser(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonSave;
    private javax.swing.JComboBox comboUserType;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel labelEmail;
    private javax.swing.JLabel labelNama;
    private javax.swing.JLabel labelPassword;
    private javax.swing.JLabel labelRePassword;
    private javax.swing.JLabel labelUserType;
    private javax.swing.JLabel labelUsername;
    private javax.swing.JPanel panelInput;
    private javax.swing.JTextField textEmail;
    private javax.swing.JTextField textName;
    private javax.swing.JPasswordField textPassword;
    private javax.swing.JPasswordField textRePassword;
    private javax.swing.JTextField textUsername;
    // End of variables declaration//GEN-END:variables
}
